package com.huantai.auth.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.Date;


@Slf4j
@Component
@RefreshScope
@Data
public class JWTUtil {

    @Value("${auth.jwt.validTime}")
    private long validTime;

    @Value("${auth.jwt.jwtKey}")
    private String key;

    @Value("${auth.jwt.issuer}")
    private String issuer;

    private static final String CLAIM_KEY = "userId";

    /**
     * 生成签名
     */
    public String generateToken(String userId){
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(key); //算法

        String token = JWT.create()
                .withIssuer(issuer) //签发人
                .withIssuedAt(now) //签发时间
                .withExpiresAt(new Date(now.getTime() + validTime)) //过期时间
                .withClaim(CLAIM_KEY, userId) //保存身份标识
                .sign(algorithm);
        return token;
    }

    /**
     * 验证token
     */
    public boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(key); //算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(issuer)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception ex){
            log.info("token verify fail：{} ", token);
        }
        return false;
    }

    /**
     * 从token获取username
     */
    public String getUser(String token){
        try{
            return JWT.decode(token).getClaim(CLAIM_KEY).asString();
        }catch(Exception ex){
            log.info("get user fail：{} ", token);
        }
        return "";
    }
}